package cn.springcloud.fix.demo.thread;

public class PrintNumberSample {

    private static volatile Integer i = 0;

    private static Object object = new Object();

    public static void main(String[] args) throws InterruptedException {
        test2();
        Thread.sleep(3000);
    }

    private static void test2() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (i < 100) {
                    synchronized (object) {
                        if (i % 2 == 0) {
                            System.out.println(i);
                            i++;
                        } else {
                            try {
                                object.notify();
                                object.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }).start();

        new Thread(() -> {
            while (i < 100) {
                synchronized (object) {
                    if (i % 2 != 0) {
                        System.out.println(i);
                        i++;
                    } else {
                        try {
                            object.notify();
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }
}
